<template>
  <div>
    <el-card class="search-card">
      <basic-table-form
        ref="formData"
        isScalingBtn
        :formColumns="formItemList"
        :dataSource="formData"
        :defaultExpandStatus="false"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
      >
      </basic-table-form>
    </el-card>
    <el-card class="table-card">
      <basic-table
        showActionCol
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :pageSizes="pageSizes"
        :tableHeight="460"
        :actionColWidth="180"
        :selectionChange="handleSelectionChange"
        :actionRender="renderTableBtnAction"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange"
      >
        <div slot="content_context">
          <el-button
            v-if="showBtn('批量提交')"
            :loading="btnLoading.batchSubmit"
            type="primary"
            size="mini"
            icon="el-icon-upload2"
            :disabled="tableInfo.selection.length === 0"
            @click="handleSubmit"
          >批量提交</el-button>
        </div>
      </basic-table>
    </el-card>
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { getBtnsId } from '@/libs/btnsPermission';
import { isResponseSuccessState, setAuthBtnId } from '@/utils/bizUtils';
import BasicTableForm from '@/components/BasicForm';
import BasicTable from '@/components/BasicTable';
import {
  FORM_ITEM_LIST,
  initTableColumns,
} from '../constants/fail';
import { getSearchParamBySearchType } from '@/utils/getUtils';
import { judgeAuthDepartmentFn } from '@/pages/commodity/modules/utils';
import { mapGetters } from 'vuex';
import { batchSubmitGoodsService } from '@api/commodity/commodityAccessManage/commodityToPerfect';

export default {
  components: {
    BasicTableForm,
    BasicTable,
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
  },
  data () {
    return {
      formItemList: FORM_ITEM_LIST,
      tableInfo: {
        list: [],
        columns: initTableColumns(this),
        loading: false,
        selection: []
      },
      pagination: {
        nowPage: 1,
        totalNum: 0,
        pageShow: 10
      },
      pageSizes: [10, 20, 30, 40],
      formData: {
        categoryPath: '',
        spuNo: '',
        productNameFinal: '',
        brandName: '',
        productType: '',
        operName: ''
      },
      apiObj: {
        // 查询审核驳回列表
        getPreparingList: {
          url: '/sysback/prepare/list/getPreparingFailList', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 跳转审核界面
        auditAndApprove: {
          url: '/sysback/oa/getAuditPageUrl',
          type: 'post'
        }
      },
      btnLoading: {
        // 批量提交按钮loading
        batchSubmit: false,
      }
    };
  },
  created () {
    this.getTableData();
  },
  methods: {
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      return <div class="table-action">
        <el-button type="text" onClick={() => this.viewRecord(row)}>查看单据</el-button>
        <el-button type="text" onClick={() => this.handleClickMore(row)}>审批记录</el-button>
        <el-button type="text" onClick={() => this.handleDeleteRow(row)}>删除</el-button>
      </div>;
    },
    // 获取表单内容
    getFormData (data) {
      this.formData = data;
    },
    // 表格勾选
    handleSelectionChange (list) {
      this.tableInfo.selection = list;
    },
    // 批量提交
    handleSubmit () {
      // 验归属部门方法
      const canSubmit = judgeAuthDepartmentFn(this.tableInfo.selection);
      if (!canSubmit) {
        return;
      }
      const productUuids = this.tableInfo.selection.map(item => item.uuid).join(',');
      this.$confirm(
        '确认提交吗？',
        { title: '提交', type: 'warning' }
      ).then(() => {
        this.batchSubmitGoods({ productUuids });
      }).catch(() => {});
    },
    // 批量提交请求
    async batchSubmitGoods (data) {
      setAuthBtnId('批量提交');
      const loadingFn = state => { this.btnLoading.batchSubmit = state };
      const res = await batchSubmitGoodsService(data, loadingFn);
      if (res) {
        this.$message.success('批量提交成功');
        await this.$router.push({ name: 'commodityPending' });
      }
    },
    // 表单查询
    handleQueryForm () {
      this.pagination.nowPage = 1;
      this.getTableData();
    },
    // 页码切换
    handlePageChange (val) {
      this.pagination.nowPage = val;
      this.getTableData();
    },
    // 每页条数切换
    handlePageSizeChange (val) {
      this.pagination.pageShow = val;
      this.getTableData();
    },
    getTableData () {
      let data = {
        searchParam: JSON.stringify([
          ...getSearchParamBySearchType(FORM_ITEM_LIST, this.formData),
          // 查询归属部门
          { name: 'belongToDepartmentFlag', value: '1' },
          // 是否是集团总部 0:不是 1:是
          { name: 'groupFlag', value: '1' }
        ]),
        ...this.pagination
      };
      const curBtnId = getBtnsId('查询');
      sessionStorage.setItem('buttonId', curBtnId);
      this.tableInfo.loading = true;
      ApiRequest(
        this.apiObj.getPreparingList.url,
        this.apiObj.getPreparingList.type,
        data,
        false
      ).then((res) => {
        this.tableInfo.loading = false;
        if (res.retStatus === '1') {
          const { totalNum, results } = res.retData
          results.forEach(item => {
            item.productUuid = item.addStateDTO ? item.addStateDTO.productUuid : ''
          })
          this.tableInfo.list = results;
          this.pagination.totalNum = totalNum;
        }
      });
    },
    // 跳转OA
    handleClickMore (row) {
      let curBtnId = getBtnsId('审核');
      sessionStorage.setItem('buttonId', curBtnId);
      // 跳转审批界面
      ApiRequest(
        this.apiObj.auditAndApprove.url + `?oaRequestId=` + row.workflowRequestId,
        this.apiObj.auditAndApprove.type
      )
        .then((res) => {
          window.open(res.retData);
        })
        .catch((err) => {
          this.$Message.error(err);
        });
    },
    // 查看单据
    viewRecord (row) {
      this.$router.push({
        path: '/commodity/commodityAccessManage/waitAccess/auditing/auditingView',
        query: { recordNo: row.recordNo }
      });
    },
    // 删除表格row
    handleDeleteRow (row) {
      this.$Modal.confirm({
        title: '删除',
        content: '删除后将把该商品的所有完善信息删除，您确认吗？',
        onOk: () => {
          this.getRequestDeleteRow({
            url: `/sysback/prepareDelete/deletePreparingSpu?productUuid=${row.productUuid}`,
            type: 'get'
          }).then(retStatus => {
            if (retStatus) {
              this.$Message.success('删除成功');
              this.getTableData();
            }
          });
        }
      });
    },
    // 删除表格row的get请求
    async getRequestDeleteRow ({ url, type, data, isFormData }) {
      try {
        this.loading = true;
        const res = await ApiRequest(url, type, data, isFormData);
        this.loading = false;
        if (isResponseSuccessState(res.retStatus)) {
          return true;
        }
      } catch (err) {
        this.loading = false;
      }
    },
    handleOpenNewPage (data) {
      const { href } = this.$router.resolve(data);
      window.open(href, '_blank');
    },
    // 跳转详情
    handleJumpNewPage (name, row, state, stateStr) {
      const notJumpStateList = ['AUDITING', 'OK', 'FAIL'];
      if (notJumpStateList.includes(state)) {
        return;
      }
      switch (name) {
        case 'structureInfoAddState': // 架构信息
          this.handleOpenNewPage({
            name: 'schemaInfoToWait',
            query: { productUuid: row.productUuid, type: 'toWait' }
          });
          break;
        case 'basicInfoAddState': // 商品基本信息
          this.handleOpenNewPage({
            path: '/commodity/commodityAccessManage/waitAccess/jibenxinxi',
            query: { productUuid: row.productUuid }
          });
          break;
        case 'manageAddState': // 商品管理信息
          this.handleOpenNewPage({
            path: '/commodity/commodityAccessManage/waitAccess/information',
            query: { productUuid: row.productUuid }
          });
          break;
        case 'packageAddState': // 商品SKU(包装)信息
          this.handleOpenNewPage({
            path: '/commodity/commodityAccessManage/waitAccess/skuInformation',
            query: { productUuid: row.productUuid }
          });
          break;
        case 'supplyGoodsAddState': // 供货信息
          this.handleOpenNewPage({
            path: '/commodity/commodityAccessManage/waitAccess/gonghuoxinxi',
            query: { productUuid: row.productUuid, state: stateStr }
          });
          break;
        case 'salePriceAddState': // 售价信息
          if (row.addStateDTO && row.addStateDTO.supplyGoodsAddState === 'ADD_OK') {
            this.handleOpenNewPage({
              name: 'toBePerfectSpuSalePrice',
              query: { productUuid: row.productUuid, state: stateStr }
            });
          } else {
            return this.$Message.error('确保供货信息已完善');
          }
          break;
        case 'picAddState': // 图文信息
          this.handleOpenNewPage({
            path: '/commodity/commodityAccessManage/waitAccess/tuwenjieshao',
            query: { productUuid: row.productUuid, spuNo: row.spuNo, productName: row.productNameFinal }
          });
          break;
        case 'acceptanceAddState': // 验收标准
          this.handleAcceptanceTip(row)
          break;
        case 'qualificationAddState': // 资质信息
          this.handleOpenNewPage({
            path: '/commodity/commodityAccessManage/waitAccess/zizhixinxi',
            query: { productUuid: row.productUuid }
          });
          break;
      }
    },
    // 点击待完善验收标准提示
    handleAcceptanceTip (row) {
      this.$router.push({ name: 'batchAddAcceptanceStandard', query: { spuNo: row.spuNo } })
    },
    // 格式化link type
    formatLinkType (type) {
      let linkType = 'info';
      switch (type) {
        case 'INIT': // 待完善
          linkType = 'primary';
          break;
        case 'ADDING': // 完善中
          linkType = 'primary';
          break;
        case 'FAIL': // 审核驳回
          linkType = 'danger';
          break;
        case 'ADD_OK': // 已完善
          linkType = 'success';
          break;
        case 'AUDITING': // 审核中
          linkType = 'info';
          break;
        case 'OK': // 已完成
          linkType = 'info';
          break;
      }
      return linkType;
    }
  }
};
</script>
<style lang="less" scoped="scoped">
.marginR50 {
  margin-right: 40px;
}
</style>
